/***********************************************************************
filename:   hgeBaseSample.cpp
created:    24/9/2004
author:     Paul D Turner
*************************************************************************/
#include "hgeBaseSample.h"
#include "hgeApplication.h"
#include "hgeExceptions.h"

/*************************************************************************
Constructor
*************************************************************************/
hgeBaseSample::hgeBaseSample() :
d_sampleApp(0)
{}


/*************************************************************************
Destructor
*************************************************************************/
hgeBaseSample::~hgeBaseSample()
{
	if (d_sampleApp)
	{
		d_sampleApp->cleanup();
		delete d_sampleApp;
	}
}


/*************************************************************************
Application entry point
*************************************************************************/
int hgeBaseSample::run()
{
	try
	{
		if (initialise())
			cleanup();
	}
	catch (Exception& exc)
	{
		outputExceptionMessage(exc.getMessage().c_str());
	}
	catch (std::exception& exc)
	{
		outputExceptionMessage(exc.what());
	}
	catch (const char* exc)
	{
		outputExceptionMessage(exc);
	}
	catch(...)
	{
		outputExceptionMessage("Unknown exception was caught!");
	}

	return 0;
}


/*************************************************************************
Initialise the sample application
*************************************************************************/
bool hgeBaseSample::initialise()
{
	d_sampleApp = new hgeApplication();

	// execute the base application (which sets up the demo via 'this' and runs it.
	if (d_sampleApp->execute(this))
	{
		// signal that app initialised and ran
		return true;
	}

	// sample app did not initialise, delete the object.
	delete d_sampleApp;
	d_sampleApp = 0;

	// signal app did not initialise and run.
	return false;
}


/*************************************************************************
Cleanup the sample application.
*************************************************************************/
void hgeBaseSample::cleanup()
{
	if (d_sampleApp)
	{
		d_sampleApp->cleanup();
		delete d_sampleApp;
		d_sampleApp = 0;
	}
}


/*************************************************************************
Output a message to the user in some OS independant way.
*************************************************************************/
void hgeBaseSample::outputExceptionMessage(const char* message) const
{
#if defined(__WIN32__) || defined(_WIN32)
	MessageBoxA(0, message, "CEGUI - Exception", MB_OK|MB_ICONERROR);
#else
	std::cout << "An exception was thrown within the sample framework:" << std::endl;
	std::cout << message << std::endl;
#endif
}
